package com.example.lanouhn.firstapp.activity.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lanouhn.firstapp.R;
import com.example.lanouhn.firstapp.activity.activity.CheckInformationActivity;
import com.example.lanouhn.firstapp.activity.activity.GoodsDetailsActivity;
import com.example.lanouhn.firstapp.activity.activity.GoodsListActivity;
import com.example.lanouhn.firstapp.activity.activity.NotifyActivity;
import com.example.lanouhn.firstapp.activity.adapter.CartListAdapter;
import com.example.lanouhn.firstapp.activity.model.CartList;
import com.example.lanouhn.firstapp.activity.model.CartListSum;
import com.example.lanouhn.firstapp.activity.utils.CartListJson;
import com.example.lanouhn.firstapp.activity.utils.CartListSumJson;
import com.example.lanouhn.firstapp.activity.utils.HttpUtils;
import com.example.lanouhn.firstapp.activity.utils.SPUtils;

import java.util.List;

public class ShoppingCarFragment extends Fragment {
    //用户登录标识
    private String key;


    private Button toGoods;
    private ImageView notify;

    private ProgressBar progressBar;
    private RecyclerView recyclerView;
    private List<CartList> dataList;
    private CartListAdapter adapter;

    private CartListSum sList;
    private TextView sum;
    //动态注册广播接收器的变量类型
    private MyBroadcastReceiver myBroadcastReceiver;
    //结算
    private Button btn_settlement;

    String cut_url = "http://www.niaolema.com/mobile/index.php?act=member_cart&op=cart_";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.activity_fragment_shopping_car, null);
        //获取本地存储的key值
        key = (String) SPUtils.get(getActivity(), "log_key", "");


        //找控件
        initView(view);
        //请求网络数据
        getDataFromWeb();
        //点击事件集合
        setOnClickListener();
        return view;
    }

    private void setOnClickListener() {

        notify.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), NotifyActivity.class);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.translatein,R.anim.translateout);
            }
        });





            btn_settlement.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(), CheckInformationActivity.class);
                    startActivity(intent);
                }
            });
                notify.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), NotifyActivity.class);
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.translatein, R.anim.translateout);
                    }
                });
                toGoods.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent it = new Intent(getActivity(), GoodsListActivity.class);
                        startActivity(it);

                    }
                });


            }
            /**
                 * 创建内部类来实现接收广播的
                 */
        class MyBroadcastReceiver extends BroadcastReceiver {


            @Override
            public void onReceive(Context context, Intent intent) {
                getDataFromWeb();


            }
        }


        @Override
        public void onActivityCreated (@Nullable Bundle savedInstanceState){
            super.onActivityCreated(savedInstanceState);
            //动态注册广播接收器
            myBroadcastReceiver = new MyBroadcastReceiver();
            //过滤器
            IntentFilter mFilter = new IntentFilter();
            mFilter.addAction("aaaaa");
            //注册
            getActivity().registerReceiver(myBroadcastReceiver, mFilter);

        }

        /**
         * 请求网路数据，开启新线程
         */
        private void getDataFromWeb () {
            progressBar.setVisibility(View.VISIBLE);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String url = cut_url + "list";
                    String params = "key=" + key;
                    String result = HttpUtils.doPost(url, params);
                    dataList = CartListJson.getCartList(result);

                    //解析商品价格的总和
                    String url_sum = cut_url + "info";
                    String result_sum = HttpUtils.doPost(url_sum, params);
                    sList = CartListSumJson.getCartListSum(result_sum);

                    //判断解析出的集合长度,有数据就显示,无数据就不显示
                    if (dataList.toString().length() > 0)
                        handler.sendEmptyMessage(1);
                    else
                        handler.sendEmptyMessage(0);
                }
            }).start();
        }

        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                progressBar.setVisibility(View.GONE);
                switch (msg.what) {
                    case 0:
                        Toast.makeText(getActivity(),
                                "请求失败,请稍候再试!!!", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
//                    获取数据成功,并解析数据成功,创建adapter
                        adapter = new CartListAdapter(getActivity(), dataList);
                        //设置adapter
                        recyclerView.setAdapter(adapter);
                        sum.setText(sList.getSum());

                        //recyclerview的item的点击事件
                        adapter.setCartListRecyviewListent(new CartListAdapter.CartListRecyviewListent() {
                            @Override
                            public void onclick(View view, int postion) {
                                //跳转到商品详情页面  并且将推荐商品的id传递过去
                                Intent intent = new Intent(getActivity(), GoodsDetailsActivity.class);
                                intent.putExtra("goods_id", dataList.get(postion).getGoods_id());
                                startActivity(intent);
                            }
                        });

                        break;
                }
            }
        };

        //找控件
        private void initView (View view){

            progressBar = (ProgressBar) view.findViewById(R.id.progressBar);

            recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
            //加载布局管理器
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
            recyclerView.setLayoutManager(gridLayoutManager);
            //设置图片距离 首页的最新商品列表
            SpacesItemDecoration decoration = new SpacesItemDecoration(9);
            recyclerView.addItemDecoration(decoration);
            sum = (TextView) view.findViewById(R.id.sum);
            btn_settlement = (Button) view.findViewById(R.id.btn_settlement);
            toGoods = (Button) view.findViewById(R.id.toGoods);
            notify = (ImageView) view.findViewById(R.id.notify);

        }

        //设置recyclerView自布局之间的间距
        public class SpacesItemDecoration extends RecyclerView.ItemDecoration {

            private int space;

            public SpacesItemDecoration(int space) {
                this.space = space;
            }

            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                outRect.left = space;
                outRect.right = space;
                outRect.bottom = space;
                if (parent.getChildAdapterPosition(view) == 0) {
                    outRect.top = space;
                }
            }
        }


        @Override
        public void onDestroy () {
            super.onDestroy();

            getActivity().unregisterReceiver(myBroadcastReceiver);
        }


    }
